﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TGVR.DataHelper.BussinessObject.BookingSystem;
using MDF.Logger.Managements;
using TGVR.DataHelper.BussinessObject;
using MDF.Utilites.Helper;
using WebLibs;
using TGVR.DataHelper.BussinessLogic.BookingSystem;
using TGVR_Boot.Services;
using MDF.DataHelper.BussinessObject.UsersBO;
using System.Globalization;
using TGVR.DataHelper.BussinessLogic.Promotion;

namespace TGVR_Boot
{
    public class BK_BootBUS
    {
        #region staticMember
        /// <summary>
        /// 
        /// </summary>
        private static BK_BootBUS _instance;
        /// <summary>
        /// 
        /// </summary>
        public static BK_BootBUS Current
        {
            get { return _instance == null ? _instance = new BK_BootBUS() : _instance; }
        }
        #endregion

        public BK_Booking CreateBooking(BK_Booking booking, BK_Passenger[] passenges, BK_Ticket tkDepart,
            BK_Ticket tkReturn, int UserID)
        {
            if (booking.DiscountCode != null)
                booking.DiscountCode = booking.DiscountCode.Trim().ToUpper();
            else
                booking.DiscountCode = "";
            LogManager.GetInstance().Info("Starting booking ticket ...");
            tkDepart.FromCity = tkDepart.FromCity.Replace("'", "");
            tkDepart.ToCity = tkDepart.ToCity.Replace("'", "");
            booking.FromCity = tkDepart.FromCity.Replace(" ", "").Replace("'", "");
            booking.ToCity = tkDepart.ToCity.Replace(" ", "").Replace("'", "");
            booking.HoldToDate = DateTime.Now;
            int Total = 0;
            int iResult = (int)BookingStatus.UNKNOW;//giá trị khởi tạo
            if (booking.PaymentTypeID == 1)//thanh toán tại nhà
                booking.TotalPrice = 25000 * passenges.Count(m => m.TypeID != 3);
            if (tkReturn != null)
            {
                tkReturn.FromCity = tkReturn.FromCity.Replace("'", "");
                tkReturn.ToCity = tkReturn.ToCity.Replace("'", "");
                booking.TotalPrice *= 2;
            }

            IData context = new IData();

            try
            {
                if (tkDepart.IsPromo || (tkReturn != null && tkReturn.IsPromo))
                {
                    //vé khuyến mãi yêu cầu xuất vé ngay
                    booking.Status = (int)BookingStatus.BK_ERR_PROMO;
                }
                else
                {
                    try
                    {
                        if (tkDepart.IsHotSale == false || (tkReturn != null && tkReturn.IsHotSale == false))
                        {
                            //cần thanh toán mua vé ngay vì quá 48 tiếng trước khi đi
                            IBoot boot = null;

                            string Code = "";

                            //2. chiều # hãng
                            if (tkReturn != null &&
                                tkDepart.AirType != tkReturn.AirType)
                            {

                                #region Create booking engine1
                                LogManager.GetInstance().Info("Loai booking: 2 chieu 2 hang");
                                if (tkDepart.AirType == "vietnam")
                                {
                                    //int OutputFee_VN = Int32.Parse(new SettingDAO().GetSetting("OutputFee_VN"));
                                    //booking.TotalPrice += OutputFee_VN;
                                    //booking.OutputFee = OutputFee_VN;
                                    //LogManager.GetInstance().Info(string.Format("VietNamAirline: add output fee {0} total = {1}", OutputFee_VN, Total));
                                    boot = new ServiceBootVietnamAirline();
                                    LogManager.GetInstance().Info("VietNamAirline: dat ve di");
                                }
                                if (tkDepart.AirType == "jetstar")
                                {
                                    boot = new ServiceBootJetstar();
                                    LogManager.GetInstance().Info("JetstarBoot: dat ve di");
                                }
                                if (tkDepart.AirType == "vietjet")
                                {
                                    boot = new ServiceBootVietjet();
                                    LogManager.GetInstance().Info("VietJetBoot: dat ve di");
                                }
                                if (tkDepart.AirType == "airasia")
                                {
                                    boot = new ServiceBootAirAsia();
                                    LogManager.GetInstance().Info("AirAsianBoot: dat ve di");
                                }
                                #endregion

                                #region Booking
                                //dat ve di
                                if (string.IsNullOrEmpty(booking.rCode) || booking.rCode.IndexOf("-") == 0)//chưa đặt dc vé đi
                                {
                                    if (!string.IsNullOrEmpty(booking.rCode) && booking.rCode.IndexOf("-") == 0)
                                        LogManager.GetInstance().Info("Book again depart ticket");
                                    iResult = boot.MakeBooking(booking, passenges, tkDepart, null, UserID);
                                    booking.HoldToDate = boot.GetHoldToDate();
                                    //cập nhật thông tin book vé
                                    Total += boot.GetTotal();
                                    Code = boot.GetCode();
                                    booking.Status = iResult;
                                    if (iResult > 0 && Total > 0 && Code != "")
                                    {
                                        // book ve thanh cong
                                        booking.rTotal = Total.ToString("#,##0");
                                        booking.rCode = Code;
                                        LogManager.GetInstance().Info("OK Depart booking successfull: " + Code + ": " + Total);
                                    }
                                    else
                                    {
                                        LogManager.GetInstance().Error("Booking fail");
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "booking", booking.Dump()));
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "passenges", passenges.Dump()));
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "tkDepart", tkDepart.Dump()));
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "tkReturn", tkReturn.Dump()));
                                    }
                                }

                                #endregion

                                #region Create booking engine 2
                                LogManager.GetInstance().Info("Loại booking: 2 chiều 2 hãng");
                                if (tkReturn.AirType == "vietnam")
                                {
                                    //int OutputFee_VN = Int32.Parse(new SettingDAO().GetSetting("OutputFee_VN"));
                                    //booking.TotalPrice += OutputFee_VN;
                                    //booking.OutputFee = OutputFee_VN;
                                    //LogManager.GetInstance().Info(string.Format("VietNamAirline: add output fee {0} total = {1}", OutputFee_VN, Total));
                                    boot = new ServiceBootVietnamAirline();
                                    LogManager.GetInstance().Info("VietNamAirline: dat ve ve");
                                }
                                if (tkReturn.AirType == "jetstar")
                                {
                                    boot = new ServiceBootJetstar();
                                    LogManager.GetInstance().Info("JetstarBoot: dat ve ve");
                                }
                                if (tkReturn.AirType == "vietjet")
                                {
                                    boot = new ServiceBootVietjet();
                                    LogManager.GetInstance().Info("VietJetBoot: dat ve ve");
                                }
                                if (tkReturn.AirType == "airasia")
                                {
                                    boot = new ServiceBootAirAsia();
                                    LogManager.GetInstance().Info("AirAsianBoot: dat ve ve");
                                }
                                #endregion

                                #region Booking
                                booking.FromCity = tkReturn.FromCity.Replace(" ", "");
                                booking.ToCity = tkReturn.ToCity.Replace(" ", "");
                                //dat ve ve
                                if (booking.rCode.IndexOf("-") == -1 && !string.IsNullOrEmpty(booking.rCode))//chưa đặt dc vé về
                                {
                                    iResult = boot.MakeBooking(booking, passenges, null, tkReturn, UserID);
                                    if (booking.HoldToDate >= boot.GetHoldToDate())
                                        booking.HoldToDate = boot.GetHoldToDate();
                                    //cập nhật thông tin book vé
                                    Total += boot.GetTotal();
                                    Code = boot.GetCode();
                                    booking.Status = iResult;
                                    if (iResult > 0 && Total > 0 && Code != "")
                                    {
                                        booking.rTotal = Total.ToString("#,##0");
                                        booking.rCode += " - " + Code;
                                        LogManager.GetInstance().Info("dat ve ve thanh cong: " + Code + ": " + Total);
                                    }
                                    else
                                    {
                                        LogManager.GetInstance().Error("Booking fail");
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "booking", booking.Dump()));
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "passenges", passenges.Dump()));
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "tkDepart", tkDepart.Dump()));
                                        LogManager.GetInstance().Error(string.Format("{0}: {1}", "tkReturn", tkReturn.Dump()));
                                    }
                                }

                                #endregion
                            }
                            else
                            { // 1 chiều or 2 chiều cùng hãng
                                #region Create booking engine 2 chiều
                                LogManager.GetInstance().Info("Booking type: same firm || one way");
                                if (tkDepart.AirType == "vietnam")
                                {
                                    //int OutputFee_VN = Int32.Parse(new SettingDAO().GetSetting("OutputFee_VN"));
                                    //booking.TotalPrice += OutputFee_VN;
                                    //booking.OutputFee = OutputFee_VN;
                                    //LogManager.GetInstance().Info(string.Format("VietNamAirline: add output fee {0} total = {1}", OutputFee_VN, Total));
                                    boot = new ServiceBootVietnamAirline();
                                    LogManager.GetInstance().Info("VietNamAirline: booking 2 ways");
                                }
                                if (tkDepart.AirType == "jetstar")
                                {
                                    boot = new ServiceBootJetstar();
                                    LogManager.GetInstance().Info("JetstarBoot: booking 2 ways");
                                }
                                if (tkDepart.AirType == "vietjet")
                                {
                                    boot = new ServiceBootVietjet();
                                    LogManager.GetInstance().Info("VietJetBoot: booking 2 ways");
                                }
                                if (tkDepart.AirType == "airasia")
                                {
                                    boot = new ServiceBootAirAsia();
                                    LogManager.GetInstance().Info("AirAsianBoot: booking 2 ways");
                                }
                                #endregion
                                //dat ve di
                                try
                                {
                                    iResult = boot.MakeBooking(booking, passenges, tkDepart, tkReturn, UserID);
                                    booking.HoldToDate = boot.GetHoldToDate();
                                    if (booking.HoldToDate.Year == 1)
                                        booking.HoldToDate = DateTime.Now;
                                    //cập nhật thông tin book vé
                                    Total += boot.GetTotal();
                                    Code = boot.GetCode();
                                    booking.Status = iResult;
                                    if (iResult > 0 && Total > 0 && Code != "")
                                    {
                                        booking.rTotal = Total.ToString("#,##0");
                                        booking.rCode = Code;
                                    }
                                    else
                                    {
                                        LogManager.GetInstance().Error("Booking BUS failed");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogManager.GetInstance().Error("Booking error!", ex);
                                }
                            }
                        }
                        else
                        {
                            booking.Status = iResult;
                            booking.rCode += "HotSale: ";
                            LogManager.GetInstance().Warn("Hot seat ticket");
                        }
                    }
                    catch (Exception ex)
                    {
                        booking.Status = iResult;
                        //booking.rCode += ex.Message + " : " + ex.StackTrace;
                        LogManager.GetInstance().Error("Booking error:", ex);
                    }
                }
                if (booking.Status > 0)
                {
                    LogManager.GetInstance().Info("Booking successful!");
                    booking.Status = (int)BookingStatus.BOOKED;
                }
                else
                {
                    LogManager.GetInstance().Warn("Booking failed!");
                }
                LogManager.GetInstance().Info(string.Format("Saving booking... {0}: {1}", booking.rCode, booking.rTotal));
                context.Connect();
                try
                {
                    context.Transaction = context.GetConnection().BeginTransaction();

                    BK_BookingBUS bkBUS = new BK_BookingBUS();
                    bkBUS.ObjData = context;
                    BK_PassengerBUS paBUS = new BK_PassengerBUS();
                    paBUS.ObjData = context;
                    BK_BookingDetailBUS bdBUS = new BK_BookingDetailBUS();
                    bdBUS.ObjData = context;

                    //booking.Status = 1;
                    booking.FromCity = tkDepart.FromCity;
                    booking.ToCity = tkDepart.ToCity;
                    booking.FlightDepart = tkDepart.FlightNo;
                    booking.Amount = 0;

                    if (tkReturn != null)
                    {
                        booking.Ways = 2;
                        booking.FlightReturn = tkReturn.FlightNo;
                    }
                    else
                        booking.Ways = 1;
                    //1. create booking
                    if (UserID == -1 && booking.UserId<1)
                        booking.UserId = 36;

                    //check promo
                    if (booking.FlightReturn == null || booking.FlightDepart.Substring(0, 2).ToLower() != "vj"
                        || booking.FlightReturn.Substring(0, 2).ToLower() != "vj"
                        )
                    {
                        booking.DiscountCode = "";
                    }

                    PRO_DiscountDetailBUS proBUS = new PRO_DiscountDetailBUS();
                    proBUS.ObjData = context;
                    booking.DiscountPrice = proBUS.GetDiscountPrice(booking.DiscountCode);
                    if (booking.DiscountPrice > 0)
                    {
                        booking.DiscountPrice *= passenges.Count(m => m.TypeID == 1);
                    }

                    booking.ID = bkBUS.Insert(booking);
                    if (booking.ID == 0)
                    {
                        context.Transaction.Rollback();
                        LogManager.GetInstance().Error(string.Format("Cant save {0}: {1}", "booking", booking.Dump()));
                        return null;
                    }
                    //2. Create passenges
                    //type: 1,2,3 : Adut, Child, Baby
                    foreach (var p in passenges)
                    {
                        p.ID = paBUS.Insert(p);
                        if (p.ID == 0)
                        {
                            context.Transaction.Rollback();
                            LogManager.GetInstance().Error(string.Format("Cant save {0}: {1}", "passenger", p.Dump()));
                            return null;
                        }
                    }
                    TK_FirmBUS fBUS = new TK_FirmBUS();
                    fBUS.ObjData = context;

                    #region Save Tickets
                    //3. Save tickets
                    BK_TicketBUS tkDAO = new BK_TicketBUS();
                    tkDAO.ObjData = context;
                    BK_Ticket tDepart = new BK_Ticket();
                    tDepart.EndDate = tkDepart.EndDate;
                    tDepart.StartDate = tkDepart.StartDate;
                    tDepart.FlightNo = tkDepart.FlightNo;
                    tDepart.FromCity = tkDepart.FromCity;
                    tDepart.ToCity = tkDepart.ToCity;
                    tDepart.Price = tkDepart.Price;
                    tDepart.PriceBefore = tkDepart.PriceBefore;
                    tDepart.Tax = tkDepart.Price - tkDepart.PriceBefore - tkDepart.Profit;
                    tDepart.TypeID = 1;
                    tDepart.BookingID = booking.ID;
                    tDepart.FirmID = fBUS.GetFirmByShortName(tDepart.FlightNo.Substring(0, 2)).ID;
                    tDepart.HoldToDate = tkDepart.HoldToDate;
                    tDepart.Class = tkDepart.Class;
                    tDepart.ID = tkDAO.Insert(tDepart);

                    if (tDepart.ID == 0)
                    {
                        LogManager.GetInstance().Error(string.Format("Cant save {0}: {1}", "tDepart", tDepart.Dump()));
                        context.Transaction.Rollback();
                        return null;
                    }
                    BK_Ticket tReturn = null;
                    if (tkReturn != null)
                    {
                        tReturn = new BK_Ticket();
                        tReturn.StartDate = tkReturn.StartDate;
                        tReturn.EndDate = tkReturn.EndDate;
                        tReturn.FlightNo = tkReturn.FlightNo;
                        tReturn.FromCity = tkReturn.FromCity;
                        tReturn.ToCity = tkReturn.ToCity;
                        tReturn.Price = tkReturn.Price;
                        tReturn.PriceBefore = tkReturn.PriceBefore;
                        tReturn.Tax = tkReturn.Price - tkReturn.PriceBefore - tkReturn.Profit;
                        tReturn.TypeID = 2;
                        tReturn.BookingID = booking.ID;
                        tReturn.HoldToDate = tkReturn.HoldToDate;


                        var firm = fBUS.GetFirmByShortName(tReturn.FlightNo.Substring(0, 2));
                        if (firm != null)
                            tReturn.FirmID = firm.ID;
                        else
                            LogManager.GetInstance().Warn("Dont have the firm " + tReturn.FlightNo);

                        tReturn.ID = tkDAO.Insert(tReturn);
                        if (tReturn.ID == 0)
                        {
                            LogManager.GetInstance().Error(string.Format("Cant save {0}: {1}", "tkReturn", tReturn.Dump()));
                            context.Transaction.Rollback();
                            return null;
                        }
                    }
                    #endregion
                    booking.FlightInfo = bkBUS.GetFlightInfo(booking.ID);
                    //4. Create booking detail
                    var objBaggage = new BK_BaggageBUS();
                    objBaggage.ObjData = context;
                    foreach (var p in passenges)
                    {
                        if (p.TypeID == 1 || p.TypeID == 2 || p.TypeID == 3)
                        {
                            BK_BookingDetail depart = new BK_BookingDetail();
                            depart.BookingID = booking.ID;
                            depart.PassengerID = p.ID;
                            depart.FromCity = tkDepart.FromCity;
                            depart.ToCity = tkDepart.ToCity;
                            depart.StartDate = tkDepart.StartDate;
                            depart.TicketID = tDepart.ID;
                            depart.Handbag = 7;
                            depart.Regbag = 0;
                            if (tkDepart.FlightNo.Substring(0, 2).ToLower() == "vn")
                                depart.Regbag = 20;
                            int iPrice = (int)tkDepart.Price;
                            depart.FlightNo = tkDepart.FlightNo;
                            int Discountfirm = fBUS.GetDisCountByTirm(tkDepart.FlightNo.Substring(0, 2).ToLower(), p.TypeID);
                            iPrice = (Discountfirm * iPrice) / 100;
                            booking.TotalPrice += iPrice;
                            #region Cal baggae
                            if (p.BaggageDepartID > 0)
                            {
                                booking.TotalPrice += objBaggage.Get(p.BaggageDepartID).Money;
                            }
                            if (p.BaggageReturnID > 0)
                            {
                                booking.TotalPrice += objBaggage.Get(p.BaggageReturnID).Money;
                            }
                            #endregion
                            depart.Price = iPrice;
                            booking.Amount++;
                            if (!bdBUS.Insert(depart))
                            {
                                context.Transaction.Rollback();
                                LogManager.GetInstance().Error(string.Format("Cant save {0}: {1}", "depart", depart.Dump()));
                                return null;
                            }
                            if (tkReturn != null)
                            {
                                BK_BookingDetail dReturn = new BK_BookingDetail();
                                dReturn.BookingID = booking.ID;
                                dReturn.PassengerID = p.ID;
                                dReturn.FromCity = tkReturn.FromCity;
                                dReturn.ToCity = tkReturn.ToCity;
                                dReturn.FlightNo = tkReturn.FlightNo;
                                dReturn.StartDate = tkReturn.StartDate;
                                dReturn.TicketID = tReturn.ID;
                                dReturn.Handbag = 7;
                                dReturn.Regbag = 0;
                                if (dReturn.FlightNo.Substring(0, 2).ToLower() == "vn")
                                    dReturn.Regbag = 20;
                                iPrice = (int)tkReturn.Price;
                                Discountfirm = fBUS.GetDisCountByTirm(tkReturn.FlightNo.Substring(0, 2).ToLower(), p.TypeID);
                                iPrice = (Discountfirm * iPrice) / 100;
                                booking.TotalPrice += iPrice;
                                dReturn.Price = iPrice;
                                booking.Amount++;
                                if (!bdBUS.Insert(dReturn))
                                {
                                    context.Transaction.Rollback();
                                    LogManager.GetInstance().Error(string.Format("Cant save {0}: {1}", "dReturn", dReturn.Dump()));
                                    return null;
                                }
                            }
                        }
                    }
                    //5. Update total price booking
                    if (booking.TotalPrice < Total)
                    {
                        LogManager.GetInstance().Warn("Change price!");
                        booking.Status = (int)BookingStatus.CHANGEDPRICE;
                    }

                    //Cal discount
                    if (booking.DiscountPrice > 0)
                    {
                        booking.TotalPrice -= booking.DiscountPrice;
                    }
                    if (!bkBUS.Update(booking))
                    {
                        context.Transaction.Rollback();
                        LogManager.GetInstance().Error(string.Format("Cant update {0}: {1}", "booking", booking.Dump()));
                        return booking;
                    }
                    LogManager.GetInstance().Info("Saved booking " + booking.rCode);
                    context.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    context.Transaction.Rollback();
                    throw ex;
                }
            }
            finally
            {
                context.DeConnect();
            }

            return booking;
        }
        public void ImportBooking(string bookingInfo, UserProfile CurrentUser)
        {
            string[] arrTemp = bookingInfo.Trim().Split('\n');
            string code;

            BK_Booking booking = new BK_Booking();
            List<BK_BookingDetail> lstBookingDetails = new List<BK_BookingDetail>();
            List<BK_Ticket> lstTickets = new List<BK_Ticket>();
            List<BK_Passenger> lstPassengers = new List<BK_Passenger>();

            List<BK_Baggage> lstBaggage = BK_BaggageBUS.Current.GetAll();
            List<TK_Firm> lstFirm = TK_FirmBUS.Current.GetAll();

            for (int i = 0; i < arrTemp.Length - 1; i++)
            {
                string line = arrTemp[i].Trim().ToUpper();
                if (string.IsNullOrEmpty(line))
                    break;
                //Find code
                if (line.IndexOf("CODE") == 0)
                {
                    code = line.Split(' ')[1].Trim();
                    booking.rCode = code;
                    booking.Address = CurrentUser.Address;
                    booking.Email = CurrentUser.Email == null ? "thegioivere@gmail.com" : CurrentUser.Email;
                    booking.Name = CurrentUser.Name;
                    booking.Note = "Add by " + CurrentUser.UserName;
                    booking.PaymentTypeID = 1;
                    booking.Phone = CurrentUser.Phone;
                    booking.SessionID = "Added Manual";
                    booking.Status = 1;
                    booking.UserId = CurrentUser.UserId;
                    booking.HoldToDate = DateTime.Now;
                    booking.IP = "0";

                    //booking.rTotal = "";
                    //booking.Total = "";
                    //booking.TotalPrice = "";
                    //booking.Ways = "";
                }
                else
                    //Find passengers
                    if (line[0] == '1' || line[0] == '2' || line[0] == '3')
                    {
                        BK_Passenger p = new BK_Passenger();
                        string PassengerName = line.Substring(1, line.IndexOf('(') - 1).Trim();
                        string TypeID = line.Substring(0, 1);
                        string DepartBaggageValue = line.Substring(line.IndexOf('(') + 1, line.IndexOf("KG") - line.IndexOf('(') - 1);
                        string ReturnBaggageValue = "";
                        if (line.IndexOf('-') > -1)
                            ReturnBaggageValue = line.Substring(line.IndexOf('-') + 1, line.LastIndexOf("KG") - line.IndexOf('-') - 1);
                        p.Name = PassengerName;
                        p.FirstName = p.Name.Split(' ')[0];
                        int iTemp = p.Name.IndexOf(' ') + 1;
                        p.Name = p.Name.Substring(iTemp + 1, p.Name.Length - iTemp - 1);
                        p.TypeID = Int32.Parse(TypeID);
                        p.BaggageDepartValue = Int32.Parse(DepartBaggageValue);
                        p.BaggageReturnValue = Int32.Parse(ReturnBaggageValue);
                        p.Address = CurrentUser.Address;
                        switch (p.TypeID)
                        {
                            case 1:
                                p.Birthday = DateTime.Now.AddYears(-20);
                                break;
                            case 2:
                                p.Birthday = DateTime.Now.AddYears(-10);
                                break;
                            case 3:
                                p.Birthday = DateTime.Now.AddYears(-1);
                                break;
                        }
                        p.City = "HCM";
                        p.CreatedDate = DateTime.Now;
                        p.Email = booking.Email;
                        p.TK_CountryID = 234;
                        p.TK_ProvineID = 10241;
                        p.Phone = CurrentUser.Phone;
                        p.Sex = "F";
                        lstPassengers.Add(p);
                        //5294	3	HUY HOANG	2013-12-19 00:00:00.000	M	HO	90 La Xuan Oai Quan 9 Tp Ho Chi Minh	HCM	234	10241	thanhlinh06hue@gmail.com	0968190579		0	NULL	0	1	0	20	0	2014-08-11 19:00:40.657	0	NULL
                    }
                    else
                    {
                        //Find tickets
                        BK_Ticket t = new BK_Ticket();
                        string[] arrTempTicket = line.Split(' ');
                        //strTemp += "VJ8382 SGN DAD 24/08 10:20 11:20 675\n";
                        string price = arrTempTicket[arrTempTicket.Length - 1];
                        string EndTime = arrTempTicket[arrTempTicket.Length - 2];
                        string StartTime = arrTempTicket[arrTempTicket.Length - 3];
                        string StartDate = arrTempTicket[arrTempTicket.Length - 4];
                        string To = arrTempTicket[arrTempTicket.Length - 5];
                        string From = arrTempTicket[arrTempTicket.Length - 6];
                        string FlightNo = "";
                        for (int j = 0; j < arrTempTicket.Length - 6; j++)
                            FlightNo += arrTempTicket[j];

                        //ID	BookingID	FirmID	FlightNo	StartDate	EndDate	Price	TypeID	IsDeleted	FromCity	ToCity	DeletedDate	HoldToDate	PriceBefore	Tax
                        //4101	2952	        1	VN1264	2014-10-18 10:50:00.000	2014-10-18 12:35:00.000	1365000	1	0	SGN	VII	NULL	2014-08-12 07:09:51.540	1150000	175000
                        t.FirmID = lstFirm.First(m => m.Name.ToLower().IndexOf(FlightNo.Substring(0, 2).ToLower()) > -1).ID;
                        t.FlightNo = FlightNo;
                        t.StartDate = DateTime.ParseExact(StartDate + " " + StartTime, "dd/MM HH:mm", CultureInfo.InvariantCulture);
                        t.EndDate = DateTime.ParseExact(StartDate + " " + EndTime, "dd/MM HH:mm", CultureInfo.InvariantCulture);
                        if (t.EndDate < t.StartDate)
                            t.EndDate.AddDays(1);
                        t.Price = Int32.Parse(price) * 1000;
                        t.TypeID = lstTickets.Count + 1;
                        t.FromCity = From;
                        t.ToCity = To;
                        t.HoldToDate = DateTime.Now.AddHours(24);
                        t.PriceBefore = t.Price;
                        t.Tax = 0;

                        for (int j = 0; j < arrTempTicket.Length - 2; j++)
                            booking.FlightInfo += arrTempTicket[j] + " ";
                        booking.FlightInfo += "<br>";
                        lstTickets.Add(t);
                    }

            }
            booking.rTotal = (Int32.Parse(arrTemp[arrTemp.Length - 1]) * 1000).ToString("#,##0");
            booking.FlightDepart = lstTickets[0].FlightNo;
            booking.FromCity = lstTickets[0].FromCity;
            booking.ToCity = lstTickets[0].ToCity;
            bool IsDemestic = !TK_StationBUS.Current.IsInter(booking.FromCity, booking.ToCity);
            foreach (var p in lstPassengers)
            {
                var DepartBag = lstBaggage.First(m => m.IsDomestic == IsDemestic
                    && m.Baggage == p.BaggageDepartValue && m.FirmID == lstTickets[0].FirmID);
                p.BaggageDepartID = DepartBag.ID;
                booking.TotalPrice += DepartBag.Money;
                if (lstTickets.Count == 2)
                {
                    var ReturnBag = lstBaggage.First(m => m.IsDomestic == IsDemestic
                    && m.Baggage == p.BaggageReturnValue && m.FirmID == lstTickets[1].FirmID);
                    p.BaggageReturnID = ReturnBag.ID;
                    booking.TotalPrice += ReturnBag.Money;
                }

            }
            booking.Ways = 1;
            if (lstTickets.Count == 2)
            {
                booking.FlightReturn = lstTickets[1].FlightNo;
                booking.Ways = 2;
            }


            IData context = new IData();
            context.Connect();
            try
            {
                context.Transaction = context.GetConnection().BeginTransaction();

                //Insert Booking
                BK_BookingBUS objBookingBUS = new BK_BookingBUS();
                BK_TicketBUS objTicketBUS = new BK_TicketBUS();
                BK_PassengerBUS objPassengerBUS = new BK_PassengerBUS();
                BK_BookingDetailBUS objBookingDetailBUS = new BK_BookingDetailBUS();
                objBookingBUS.ObjData = context;
                objTicketBUS.ObjData = context;
                objPassengerBUS.ObjData = context;
                objBookingDetailBUS.ObjData = context;
                booking.Amount = lstTickets.Count * lstPassengers.Count;

                booking.ID = objBookingBUS.Insert(booking);
                if (booking.ID == 0)
                {
                    context.Transaction.Rollback();
                    return;
                }

                foreach (var t in lstTickets)
                {
                    t.BookingID = booking.ID;
                    t.ID = objTicketBUS.Insert(t);
                    if (t.ID == 0)
                    {
                        context.Transaction.Rollback();
                        return;
                    }

                    foreach (var p in lstPassengers)
                    {
                        booking.Amount++;
                        p.ID = objPassengerBUS.Insert(p);
                        if (p.ID == 0)
                        {
                            context.Transaction.Rollback();
                            return;
                        }
                        BK_BookingDetail detail = new BK_BookingDetail();
                        detail.BookingID = booking.ID;
                        detail.FlightNo = t.FlightNo;
                        detail.FromCity = t.FromCity;
                        detail.PassengerID = p.ID;
                        var firm = lstFirm.First(m => m.ID == t.FirmID);
                        switch (p.TypeID)
                        {
                            case 1:
                                detail.Price = t.Price * firm.Adult / 100;
                                break;
                            case 2:
                                detail.Price = t.Price * firm.Child / 100;
                                break;
                            case 3:
                                detail.Price = t.Price * firm.Baby / 100;
                                break;
                            default:
                                detail.Price = t.Price;
                                break;
                        }
                        detail.StartDate = t.StartDate;
                        detail.TicketID = t.ID;
                        detail.ToCity = t.ToCity;
                        if (!objBookingDetailBUS.Insert(detail))
                        {
                            context.Transaction.Rollback();
                            return;
                        }
                        booking.TotalPrice += detail.Price;
                    }

                }
                decimal total = booking.TotalPrice;
                string flightInfo = booking.FlightInfo;
                booking = objBookingBUS.Get(booking.ID);
                booking.TotalPrice = total;
                booking.FlightInfo = flightInfo;
                if (!objBookingBUS.Update(booking))
                {
                    context.Transaction.Rollback();
                    return;
                }
                context.Transaction.Commit();
            }
            catch (Exception ex)
            {
                context.Transaction.Rollback();
            }
            finally
            {
                context.DeConnect();
            }
        }

    }


}
